package cn.xlbweb.admincloud.util;

import java.util.HashMap;
import java.util.Map;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @author: bobi
 * @date: 2019-06-23 14:13
 * @description:
 */
@Slf4j
public class JwtUtils {

    public static final String SECRET = "abcdefghijklmnopqrstuvwxyz";
    public static final String TOKEN_PREFIX = "Bearer";
    public static final String HEADER_AUTH = "Authorization";

    /**
     * 生成token
     *
     * @param userId
     * @return
     */
    public static String generateToken(String userId) {
        Map<String, Object> map = new HashMap<>(8);
        map.put("userId", userId);
        String jwt = Jwts.builder().setSubject("user info").setClaims(map).signWith(SignatureAlgorithm.HS512, SECRET).compact();
        String token = TOKEN_PREFIX + " " + jwt;
        return token;
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public static String parseToken(String token) {
        if (StringUtils.isBlank(token)) {
            log.error("token不能为空");
            return null;
        }
        Map<String, Object> body = new HashMap<>(8);
        try {
            body = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
        } catch (ExpiredJwtException e) {
            log.error("token过期: {}", e.getMessage());
        } catch (JwtException e) {
            log.error("token解析异常: {}", e.getMessage());
        }
        String userId = String.valueOf(body.get("userId"));
        if (StringUtils.isEmpty(userId)) {
            log.error("用户不存在");
            return null;
        }
        return userId;
    }
}
